function status = SK6_Write_ACK( address, data )
% SHAKE SK6 Matlab Driver v1.00, (c) 2010 SAMH Engineering Services
%
% function status = SK6_Write_ACK( address, data )
% This function writes <data> to <address> on the SK6 and looks
% for an ACK / NAK response where both arguments are hexadecimal strings. 
% If an ACK is received true is returned
% If a NAK is received or if there is a timeout, false is returned
% <address> is the address to write to as a 4 digit hex string
% <data> is the data value to write as a 2 digit hex string
% the data is only transmitted if the CTS line is active
% if CTS was inactive or an acknowledge is not received, 0 is returned
% otherwise 1 is returned
%
% Example Usage: To set the SK6 acceleration data rate to 10Hz
% status = SK6_Write_ACK( '0008', '0A' )


% the serial port that is used is a global variable
global port

% open the sensor ID structure
IDs = SK6_Get_Sensor_IDs();

attempts = 5; % try to write 5 times before failure
header = strcat( '$WRI,' , address , ',' , data );
status = false; % return false by default
timeout = 3; % set the timeout for a response to 3 seconds ( it can be this long if a bluetooth connection is poor )

% clear the receive buffer of previous ACK packets
ack_packets = SK6_Data_Samples_Available( IDs.Ack );
SK6_Get_Sensor_Data( IDs.Ack , ack_packets );


% try the write a few times in case
while attempts > 0
  
  % make sure that CTS is active before attempting the write
  if strcmp( port.PinStatus.ClearToSend , 'off')
    fprintf( 2,'SK6 CTS is active, stalling for 20mS\n' );
  else
    % send the $WRI packet to the SK6
    fprintf( port , header );
    
    % wait for the $ACK into the COM port buffer with timeout
    tic;
    while ( SK6_Data_Samples_Available( IDs.Ack ) == 0 ) && ( toc < timeout )
      pause(0.005)% sleep to prevent busy waiting processor loading
    end
    
    if toc < timeout
      
      % read the $ACK packet
      ack_packet_data = SK6_Get_Sensor_Data( IDs.Ack , 1 );
      
      % check that the $ACK packet is correct
      if ( ack_packet_data(1) == int32(hex2dec( address )) )&&...  % the address field
          ( ack_packet_data(2) == int32(hex2dec( data   )) )&&... % the data field
          ( ack_packet_data(3) == 1 )  % the ACK / NAK field, 1 == ACK, 0 == NAK
        % $ACK returned succesfully
        status = true;
        break;
      end
    end
  end
  attempts = attempts - 1;
  pause(0.02); % SK6 not ready to receive, wait 20ms before trying again
end

if status == false
  err_string = strcat( 'SK6 write failed on address 0x', address , '\n' );
  fprintf( 1, err_string );
end

end %function SK6_Write_ACK(address,data)

